from django.shortcuts import render
from django.views.generic import View
from .models import treeHoleClass, treeHole, secret, agree, comment, imgs, reporTreason, reportAlready, topicofc, topicofc
from users.models import onceName, UserProfile
import json
from django.http import HttpResponse, JsonResponse
from TreeHoleAdminPy3.settings import MEDIA_URL
from utils.mixin_utils import LoginRequiredMixin, get_current_ip
# from django.contrib.auth.decorators import login_required
from datetime import time
import random
from .forms import commentForm, agreeForm, ReportForm, JarInformationForm, SubSecretForm

# Create your views here.


class getIndex(View):
    # 首页分类&树洞
    def get(self, request):
        all_treeHoleClass = treeHoleClass.objects.filter(show=int(True))  # 首页分类
        all_treeHole = treeHole.objects.filter(show=int(True))  # 全部树洞
        all_header = []
        all_hole = []

        for treeHoleClassLi in all_treeHoleClass:
            hole = []

            for treeHoleLi in all_treeHole:
                if treeHoleLi.treeholeclass == treeHoleClassLi:
                    HoleLi = {
                        "id": treeHoleLi.id,
                        "name": treeHoleLi.title
                    }
                    hole.append(HoleLi)
            all_header.append({
                "id": treeHoleClassLi.id,
                "title": treeHoleClassLi.title,
            })
            all_hole.append({
                "id": treeHoleClassLi.id,
                "title": treeHoleClassLi.title,
                "hole": hole
            })

        resjson = {
            "ret": True,
            "status": "success",
            "msg": "ok",
            "data": {
                "header": all_header,
                "tree_hole": all_hole
            }
        }
        return HttpResponse(json.dumps(resjson), content_type='application/json')


class getSecret_list(View):
    # 秘密列表
    def get(self, request):
        ip = get_current_ip()
        Treehole_id = request.GET.get('Treehole_id')
        last_num = int(request.GET.get('last_num'))
        next_page = int(request.GET.get('next_page'))
        sex = request.GET.get('Treehole_sex')
        age = request.GET.get('Treehole_age')
        treeHoleLi = treeHole.objects.get(id=int(Treehole_id))  # 获取秘密所在树洞
        if sex:
            if request.user.id:
                sexUser = request.user.sex
                if int(sex) == 0:
                    sexScreen = sexUser
                else:
                    sexScreen = int(not bool(sexUser))
                if age:
                    all_secret = secret.objects.filter(show=int(True), treeHole__id=treeHoleLi.id, onceName__user__sex=sexScreen, onceName__user__years=age)[last_num:next_page]
                else:
                    all_secret = secret.objects.filter(show=int(True), treeHole__id=treeHoleLi.id, onceName__user__sex=sexScreen)[last_num:next_page]
            else:
                resjson = {
                    "ret": True,
                    "status": "notLogin",
                    "msg": "用户未登录"
                }
                return HttpResponse(json.dumps(resjson), content_type='application/json')
        elif age:
            all_secret = secret.objects.filter(show=int(True), treeHole__id=treeHoleLi.id, onceName__user__years=age)[last_num:next_page]
        else:
            all_secret = secret.objects.filter(show=int(True), treeHole__id=treeHoleLi.id)[last_num:next_page]



        AllSecretLi = []
        for secretLi in all_secret:
            all_comment = comment.objects.filter(secret__id=int(secretLi.id), show=True)  # 获取当前秘密评论
            all_agree = agree.objects.filter(secret__id=int(secretLi.id), show=True)  # 获取当前秘密所有点赞
            all_img = imgs.objects.filter(secret__id=int(secretLi.id))  # 获取当前秘密所有点赞
            imgsLi = []
            for imgLi in all_img:
                imgsLi.append(MEDIA_URL + str(imgLi.img))

            if secretLi.topicofc == None:
                word = ""
                wordId = ""
            else:
                topicofcLi = secretLi.topicofc
                word = topicofcLi.content
                wordId = topicofcLi.id

            if not request.user.id:
                agreeUser = 0
            else:
                try:
                    agreeUser = agree.objects.get(user__id=request.user.id, secret__id=int(secretLi.id), show=True)  # 获取当前用户是否给当前秘密点赞
                except agree.DoesNotExist:
                    agreeUser = 0
                else:
                    agreeUser = 1

            AllSecretLi.append({
                "id": secretLi.id,
                "userId": secretLi.onceName.user.id,
                "name": secretLi.title,
                "content": secretLi.content,
                "age": secretLi.onceName.user.age,
                "sex": secretLi.onceName.user.sex,
                "word": word,
                "wordId": wordId,
                "datetime": (secretLi.time).strftime('%Y-%m-%d %H:%M:%S'),
                "likeNum": len(all_agree),
                "userLike": agreeUser,
                "likeName": secretLi.treeHole.agreeName.name,
                "commentNum": len(all_comment),
                "imgs": imgsLi
            })

        resjson = {
            "ret": True,
            "status": "success",
            "msg": "ok",
            "data": {
                "tree_hole_data": {
                    "id": treeHoleLi.id,
                    "name": treeHoleLi.title,
                    "ask": treeHoleLi.ask,
                    "text": treeHoleLi.text,
                    "input": treeHoleLi.input,
                    "data": AllSecretLi
                }
            }
        }

        return HttpResponse(json.dumps(resjson), content_type='application/json')


class getSecret(View):
    # 根据ID查询秘密
    def get(self, request):
        secret_id = request.GET.get('secret_id')
        next_page = request.GET.get('next_page')
        secretLi = secret.objects.get(show=int(True), id=secret_id)  # 秘密

        all_comment = comment.objects.filter(secret__id=int(secretLi.id))  # 获取当前秘密评论
        all_agree = agree.objects.filter(secret__id=int(secretLi.id), show=True)  # 获取当前秘密所有点赞
        all_img = imgs.objects.filter(secret__id=int(secretLi.id))  # 获取当前秘密所有点赞
        if not request.user.id:
            agreeUser = 0
        else:
            try:
                agreeUser = agree.objects.get(user__id=request.user.id, secret__id=int(secretLi.id), show=True)  # 获取当前用户是否给当前秘密点赞
            except agree.DoesNotExist:
                agreeUser = 0
            else:
                agreeUser = 1

        AllCommentLi = []
        imgsLi = []
        for imgLi in all_img:
            imgsLi.append(MEDIA_URL + str(imgLi.img))
        for commentLi in all_comment:
            if not commentLi.SuperiorComment:
                commentReply = {}
            else:
                commentReply = {
                    "commentId": commentLi.SuperiorComment.id,
                    "userId": commentLi.SuperiorComment.onceName.user.id,
                    "userName": commentLi.SuperiorComment.onceName.name,
                    "userDatetime": (commentLi.SuperiorComment.time).strftime('%Y-%m-%d %H:%M:%S')
                }

            AllCommentLi.append({
                "commentId": commentLi.id,
                "userId": commentLi.onceName.user.id,
                "userName": commentLi.onceName.name,
                "userComment": commentLi.content,
                "userDatetime": (commentLi.time).strftime('%Y-%m-%d %H:%M:%S'),
                "commentReply": commentReply
              })

        if secretLi.topicofc == None:
            word = ""
            wordId = ""
        else:
            topicofcLi = secretLi.topicofc
            word = topicofcLi.content
            wordId = topicofcLi.id

        resjson = {
            "ret": True,
            "status": "success",
            "msg": "ok",
            "data": {
                "id": secretLi.id,
                "userId": secretLi.onceName.user.id,
                "treeHoleId": secretLi.treeHole.id,
                "treeHoleName": secretLi.treeHole.title,
                "name": secretLi.title,
                "content": secretLi.content,
                "word": word,
                "wordId": wordId,
                "datetime": (secretLi.time).strftime('%Y-%m-%d %H:%M:%S'),
                "likeNum": len(all_agree),
                "userLike": agreeUser,
                "likeName": secretLi.treeHole.agreeName.name,
                "weather": secretLi.weather,
                "temperature": secretLi.temperature,
                "imgs": imgsLi,
                "allcomment": AllCommentLi
            }
        }

        return HttpResponse(json.dumps(resjson), content_type='application/json')


class getMeet(View):
    # 随机获取秘密
    def get(self, request):
        next_page = request.GET.get('next_page')
        secretLi = secret.objects.filter(show=int(True))  # 秘密
        AllMeet = []
        for i in range(int(next_page)):
            ran = random.randint(1, len(secretLi) - 1)
            RanSecretLi = secretLi[ran]
            all_comment = comment.objects.filter(secret__id=int(RanSecretLi.id), show=True)  # 获取当前秘密评论
            all_agree = agree.objects.filter(secret__id=int(RanSecretLi.id), show=True)  # 获取当前秘密所有点赞
            all_img = imgs.objects.filter(secret__id=int(RanSecretLi.id), show=True)  # 获取当前秘密所有图片
            AllCommentLi = []
            imgsLi = []
            for imgLi in all_img:
                imgsLi.append(MEDIA_URL + str(imgLi.img))
            for commentLi in all_comment:
                if not commentLi.SuperiorComment:
                    commentReply = {}
                else:
                    commentReply = {
                        "commentId": commentLi.SuperiorComment.id,
                        "userId": commentLi.SuperiorComment.onceName.user.id,
                        "userName": commentLi.SuperiorComment.onceName.name,
                        "userDatetime": (commentLi.SuperiorComment.time).strftime('%Y-%m-%d %H:%M:%S')
                    }

                AllCommentLi.append({
                    "commentId": commentLi.id,
                    "userId": commentLi.onceName.user.id,
                    "userName": commentLi.onceName.name,
                    "userComment": commentLi.content,
                    "userDatetime": (commentLi.time).strftime('%Y-%m-%d %H:%M:%S'),
                    "commentReply": commentReply
                })
            if not request.user.id:
                agreeUser = 0
            else:
                try:
                    agreeUser = agree.objects.get(user__id=request.user.id, secret__id=int(RanSecretLi.id), show=True)  # 获取当前用户是否给当前秘密点赞
                except agree.DoesNotExist:
                    agreeUser = 0
                else:
                    agreeUser = 1

            AllMeet.append({
                "id": RanSecretLi.id,
                "userId": RanSecretLi.onceName.user.id,
                "treeHoleId": RanSecretLi.treeHole.id,
                "treeHoleName": RanSecretLi.treeHole.title,
                "name": RanSecretLi.onceName.name,
                "content": RanSecretLi.content,
                "datetime": (RanSecretLi.time).strftime('%Y-%m-%d %H:%M:%S'),
                "likeNum": len(all_agree),
                "userLike": agreeUser,
                "likeName": RanSecretLi.treeHole.agreeName.name,
                "weather": RanSecretLi.weather,
                "temperature": RanSecretLi.temperature,
                "imgs": imgsLi,
                "allcomment": AllCommentLi
            })

        resjson = {
            "ret": True,
            "status": "success",
            "msg": "ok",
            "data": AllMeet
        }

        return HttpResponse(json.dumps(resjson), content_type='application/json')


class CommentReply(LoginRequiredMixin, View):
    # 秘密评论&回复
    def post(self, request):
        comment_form = commentForm(request.POST)
        if comment_form.is_valid():
            secretId = request.POST.get('secretId', '')
            userComment = request.POST.get('userComment', '')
            commentReplyId = request.POST.get('commentReplyId', '')
            secretLi = secret.objects.get(show=int(True),id=int(secretId))  # 秘密
            if not secretLi.Interaction:
                resjson = {
                    "ret": True,
                    "status": "RefuseInteraction",
                    "msg": "该秘密禁止互动",
                    "data": []
                }
                return HttpResponse(json.dumps(resjson), content_type='application/json')

            if not commentReplyId:
                commentLi = None
            else:
                commentLi = comment.objects.get(show=int(True), id=int(commentReplyId))  # 秘密
            onceNameLi = onceName.objects.get(user__id=int(request.user.id), current=True)  # 曾用名

            commentSave = comment()
            commentSave.secret = secretLi
            commentSave.onceName = onceNameLi
            commentSave.content = userComment
            commentSave.SuperiorComment = commentLi
            commentSave.save()

            if not commentSave.SuperiorComment:
                commentReply = {}
            else:
                commentReply = {
                    "commentId": commentSave.SuperiorComment.id,
                    "userId": commentSave.SuperiorComment.onceName.user.id,
                    "userName": commentSave.SuperiorComment.onceName.name,
                    "userDatetime": (commentSave.SuperiorComment.time).strftime('%Y-%m-%d %H:%M:%S')
                }

            resjson = {
                "ret": True,
                "status": "success",
                "msg": "ok",
                "data": {
                    "commentId": commentSave.id,
                    "userId": commentSave.onceName.user.id,
                    "userName": commentSave.onceName.name,
                    "userComment": commentSave.content,
                    "userDatetime": (commentSave.time).strftime('%Y-%m-%d %H:%M:%S'),
                    "commentReply": commentReply
                  }
            }
            return HttpResponse(json.dumps(resjson), content_type='application/json')
        else:
            resjson = {
                "ret": True,
                "status": "fail",
                "msg": "评论提交参数格式错误",
                "data": []
            }
            return HttpResponse(json.dumps(resjson), content_type='application/json')


class SameQuestion(LoginRequiredMixin, View):
    # 秘密点赞
    def get(self, request):
        agree_form = agreeForm(request.GET)
        if agree_form.is_valid():
            secretId = request.GET.get('secretId', '')
            try:
                secretLi = secret.objects.get(show=int(True), id=int(secretId))  # 秘密
                onceNameLi = onceName.objects.get(user__id=int(request.user.id), current=True)  # 曾用名
                agreeUser = agree.objects.get(user__id=request.user.id, secret__id=int(secretLi.id), show=True)  # 获取当前用户是否给当前秘密点赞
            except secret.DoesNotExist:
                resjson = {
                    "ret": True,
                    "status": "fail",
                    "msg": "秘密不存在",
                    "data": []
                }
                return HttpResponse(json.dumps(resjson), content_type='application/json')
            except onceName.DoesNotExist:
                resjson = {
                    "ret": True,
                    "status": "fail",
                    "msg": "曾用名不存在",
                    "data": []
                }
                return HttpResponse(json.dumps(resjson), content_type='application/json')
            except agree.DoesNotExist:
                agreeSave = agree()
                agreeSave.user = onceNameLi.user
                agreeSave.secret = secretLi
                agreeSave.save()
            else:
                agreeUser.show = False
                agreeUser.save()

            resjson = {
                "ret": True,
                "status": "success",
                "msg": "ok"
            }
            return HttpResponse(json.dumps(resjson), content_type='application/json')
        else:
            resjson = {
                "ret": True,
                "status": "fail",
                "msg": "点赞提交参数格式错误",
                "data": []
            }
            return HttpResponse(json.dumps(resjson), content_type='application/json')


class Report(LoginRequiredMixin, View):
    # 举报
    def get(self, request):
        report_form = ReportForm(request.GET)
        if report_form.is_valid():
            secretId = request.GET.get('secretId', '')
            ReportReasonId = request.GET.get('ReportReasonId', '')
            ReportCommentId = request.GET.get('ReportCommentId', '')

            if ReportCommentId:
                try:
                    ReportCommentLi = comment.objects.get(id=int(ReportCommentId), show=True)  # 评论
                except comment.DoesNotExist:
                    resjson = {
                        "ret": True,
                        "status": "fail",
                        "msg": "评论不存在",
                        "data": []
                    }
                    return HttpResponse(json.dumps(resjson), content_type='application/json')
            else:
                ReportCommentLi = None

            try:
                secretLi = secret.objects.get(show=int(True), id=int(secretId))  # 秘密
                reportReasonLi = reporTreason.objects.get(id=int(ReportReasonId), show=True)  # 举报选项
            except secret.DoesNotExist:
                resjson = {
                    "ret": True,
                    "status": "fail",
                    "msg": "秘密不存在",
                    "data": []
                }
                return HttpResponse(json.dumps(resjson), content_type='application/json')
            except reporTreason.DoesNotExist:
                resjson = {
                    "ret": True,
                    "status": "fail",
                    "msg": "举报选项不存在",
                    "data": []
                }
                return HttpResponse(json.dumps(resjson), content_type='application/json')

            reportAlreadySave = reportAlready()
            reportAlreadySave.reporTreason = reportReasonLi
            reportAlreadySave.user = request.user
            reportAlreadySave.secret = secretLi
            reportAlreadySave.comment = ReportCommentLi
            reportAlreadySave.save()

            resjson = {
                "ret": True,
                "status": "success",
                "msg": "举报成功"
            }
            return HttpResponse(json.dumps(resjson), content_type='application/json')
        else:
            resjson = {
                "ret": True,
                "status": "fail",
                "msg": "举报提交参数格式错误",
                "data": []
            }
            return HttpResponse(json.dumps(resjson), content_type='application/json')


class JarInformation(LoginRequiredMixin, View):
    # 获取秘密信息
    def get(self, request):
        JarInformation_form = JarInformationForm(request.GET)
        if JarInformation_form.is_valid():
            TreeHole_id = request.GET.get('TreeHole_id', '')
            treeHoleModels = treeHole.objects.get(id=int(TreeHole_id))
            topicofcModels = topicofc.objects.filter(treeHole__id=int(TreeHole_id), show=True)
            once_name = onceName.objects.filter(user__id=int(request.user.id), show=True)
            ran = random.randint(1, len(once_name) - 1)
            wordList = []
            for topicofcLi in topicofcModels:
                wordList.append({
                    "wordId": topicofcLi.id,
                    "wordName": topicofcLi.content
                })

            resjson = {
                "ret": True,
                "status": "success",
                "msg": "ok",
                "data": {
                    "id": treeHoleModels.id,
                    "userName": once_name[ran].name,
                    "name": treeHoleModels.title,
                    "ask": treeHoleModels.ask,
                    "text": treeHoleModels.text,
                    "input": treeHoleModels.input,
                    "wordList": wordList
                }
            }
            return HttpResponse(json.dumps(resjson), content_type='application/json')
        else:
            resjson = {
                "ret": True,
                "status": "fail",
                "msg": "秘密获取参数格式错误",
                "data": []
            }
            return HttpResponse(json.dumps(resjson), content_type='application/json')


class SubSecret(LoginRequiredMixin, View):
    # 秘密创建
    def post(self, request):
        SubSecret_form = SubSecretForm(request.POST)
        if SubSecret_form.is_valid():
            TreeHole_id = request.POST.get('TreeHole_id', '')
            Weather = request.POST.get('Weather', '')
            Temperature = request.POST.get('Temperature', '')
            CanText = request.POST.get('CanText', '')
            WordId = request.POST.get('WordId', '')
            WSInputName = request.POST.get('WSInputName', '')
            Interaction = request.POST.get('Interaction', '')
            files = request.FILES.getlist("files")
            if WordId == 'undefined':
                topicofcModels = None
            else:
                topicofcModels = topicofc.objects.get(id=int(WordId))
            onceNameModels = onceName.objects.filter(user__id=int(request.user.id), current=True)
            TreeHoleModels = treeHole.objects.get(id=int(TreeHole_id))

            secretSave = secret()
            secretSave.treeHole = TreeHoleModels
            secretSave.onceName = onceNameModels[0]
            secretSave.topicofc = topicofcModels
            secretSave.title = WSInputName
            secretSave.weather = Weather
            secretSave.temperature = Temperature
            secretSave.content = CanText
            secretSave.Interaction = bool(int(Interaction))
            secretSave.save()

            for img in files:
                imgLi = imgs()
                imgLi.secret = secretSave
                imgLi.img = img
                imgLi.save()

            resjson = {
                "ret": True,
                "status": "success",
                "msg": "ok",
                "data": []
            }
            return HttpResponse(json.dumps(resjson), content_type='application/json')
        else:
            resjson = {
                "ret": True,
                "status": "fail",
                "msg": "秘密创建参数格式错误",
                "data": []
            }
            return HttpResponse(json.dumps(resjson), content_type='application/json')



class NotLogin(View):
    # 用户未登录
    def get(self, request):
        resjson = {
            "ret": True,
            "status": "notLogin",
            "msg": "用户未登录"
        }
        return HttpResponse(json.dumps(resjson), content_type='application/json')

